package com.intramirror.product.controller;

import com.intramirror.core.common.exception.ValidateException;
import com.intramirror.core.common.response.ErrorResponse;
import com.intramirror.core.common.response.Response;
import com.intramirror.core.common.response.StatusCode;
import com.intramirror.product.service.IOssManagementService;
import com.intramirror.product.utils.ConvertUtil;
import java.io.IOException;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created on 2018/7/6.
 * @author 123
 */
@RestController
public class OssManagementController {
    private static final Logger LOGGER = LoggerFactory.getLogger(OssManagementController.class);

    @Autowired
    IOssManagementService ossManagementService;

    @PostMapping(value = "/file")
    public Response uploadFile(@SessionAttribute(value = "user") Map<String, Object> user, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new ValidateException(new ErrorResponse("File is empty."));
        }

        try {
            String url = ossManagementService.uploadFile(file);
            Long userId = ConvertUtil.toLong(user.get("userId"));
            LOGGER.info("Upload file successful. URL: [{}], userId: {}.", url, userId);
            return Response.status(StatusCode.SUCCESS).data(url);
        } catch (IOException e) {
            throw new ValidateException(new ErrorResponse(e.getMessage()));
        }
    }
}
